package net.jxta.myjxta.plugins.secureonetoone;

import net.jxta.endpoint.Message;
import net.jxta.myjxta.MyJXTA;
import net.jxta.myjxta.View;
import net.jxta.myjxta.dialog.*;
import net.jxta.myjxta.plugin.IPluginNotificationHandler;
import net.jxta.myjxta.plugin.ISelectableNode;
import net.jxta.myjxta.plugin.PluginBase;
import net.jxta.myjxta.plugin.PluginContainer;
import net.jxta.myjxta.ui.MenuManager;
import net.jxta.myjxta.util.Group;
import net.jxta.myjxta.util.Resources;
import net.jxta.myjxta.util.objectmodel.JxtaNode;
import net.jxta.myjxta.util.objectmodel.PeerNode;
import net.jxta.peergroup.PeerGroup;
import net.jxta.pipe.PipeService;
import net.jxta.protocol.PipeAdvertisement;
import net.jxta.util.JxtaBiDiPipe;

import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ResourceBundle;

public class SecureOneToOnePlugin extends PluginBase implements IPluginNotificationHandler, PluginContainer.IPopupProvider, DialogManager.IDialogProvider {

    private static final ResourceBundle STRINGS = Resources.getStrings();

    public SecureOneToOnePlugin() {
        setName(null);
    }

    public IPluginNotificationHandler getPluginNotificationHander() {
        return this;
    }

    public void destroy() {
        super.destroy();    //To change body of overridden methods use File | Settings | File Templates.
        CommandFactory.unregisterCommand(CredentialCommand.class);
        CommandFactory.unregisterCommand(UnicastSecurePipeAdvCommand.class);
    }

    public void init(PluginContainer c) {
        super.init(c);


        CommandFactory.registerCommand(CredentialCommand.class);
        CommandFactory.registerCommand(UnicastSecurePipeAdvCommand.class);


        Dialog.registerDialogNamer(OneToOneDialog.class, new DialogNamer() {
            public String getDialogName(String s) {


                return OneToOneDialog.DIALOG_NAME +
                        Dialog.IMFREE_DELIMITER + s;
            }
        });

        DialogManager.registerDialogProvider(OneToOneDialog.class, this);

        m_container.registerPopupProvider(this);

        start(); //autostart - we want the menu entry immediately after the initialisation

    }

    public void start() {
        super.start();
        View view = m_container.getMyJxta().getView();
        MenuManager.getInstance(view).getPluginActionMap().put(MenuManager.PLUGIN_MENU_CHAT_ONE_TO_ONE_SECURE, new PeerChatAction("", view));
    }

    public void stop() {
        View view = m_container.getMyJxta().getView();
        MenuManager.getInstance(view).getPluginActionMap().remove(MenuManager.PLUGIN_MENU_CHAT_ONE_TO_ONE_SECURE);
        super.stop();
    }

    public void groupJoined(final Group p_group) {
        //on any group join we register our dialog name (--> dialog bidi-pipe) at the
        //correct dialogmanager
        if (!p_group.isVisible()) //no listeners for npg and other non-visible groups
            return;

        String dialogName1;
        PeerGroup pg = p_group.getPeerGroup();
        dialogName1 = Dialog.getDialogNamer(OneToOneDialog.class).
                getDialogName(pg.getPeerName());

        final MyJXTA myJxta = m_container.getMyJxta();
        myJxta.setStatus(STRINGS.getString("status.dialog.listener.add") +
                ": " + dialogName1);


        DialogManager dialogManager = DialogManager.getInstance(p_group, dialogName1, PipeService.UnicastSecureType);
        dialogManager.addPipeListener(p_group.getPeerGroup(), new DialogPipeListener() {
            // xxx: authenticate if not. for now, we are authenticated

            public void receive(PeerGroup pg, JxtaBiDiPipe pipe) {
                Dialog dialog = DialogManager.getDialog(OneToOneDialog.class,
                        p_group, pipe, myJxta);

                String remotePeerName = pipe.getRemotePeerAdvertisement().getName();
                if (dialog instanceof OneToOneDialog) {
                    OneToOneDialog oneToOneDialog = (OneToOneDialog) dialog;
                    oneToOneDialog.setInitialName(remotePeerName);
                }

                myJxta.addDialog(dialog);
            }

            public void receive(PeerGroup pg, Message msg) {
                System.out.println(msg.toString());
            }
        });
    }

    public void groupResigned(Group p_group) {

        if (!p_group.isVisible())
            return;


        String pn = Dialog.getDialogNamer(OneToOneDialog.class).getDialogName(p_group.getPeerGroup().getPeerName());
        m_container.getMyJxta().setStatus(STRINGS.getString("status.dialog.listener.remove") +
                ": " + pn);

        DialogManager.getInstance(p_group, pn, PipeService.UnicastSecureType).
                clearPipeListeners(p_group.getPeerGroup());
    }

    public void groupStateChanged(Group p_group) {
        //nothing in here - this method is called if we get connected/disconnected from a joined group
        //we could possibly activate/deactivate the menu here....
    }


    public void popupRequested(PluginContainer.IPopupGenerator popupGenerator, ISelectableNode[] selectedNodes, MouseEvent triggerEvent) {

        if (!isRunning())
            return;
        if (selectedNodes != null && selectedNodes.length >= 1) {
            JxtaNode jxtaNode = selectedNodes[0].getJxtaNode();
            if (jxtaNode instanceof PeerNode) {
                PluginContainer.MenuPath peerPath = new PluginContainer.MenuPath(STRINGS.getString("menu.peer"), KeyEvent.VK_P);
//                popupGenerator.addPopup(new PluginContainer.MenuPath[]{peerPath}, 3, new PeerChatAction(STRINGS.getString("menu.peer.dialog"), m_container.getMyJxta().getView()));
            }
        }
    }

    public Dialog createDialog(Group p_g, PipeAdvertisement p_pa, MyJXTA p_myjxta) {
        return new OneToOneDialog(p_g, p_pa, p_myjxta);
    }

    //other side has initiated the dialog
    public Dialog createDialog(Group p_g, JxtaBiDiPipe p_pipe, MyJXTA p_myjxta) {
        return new OneToOneDialog(p_g, p_pipe, p_myjxta);
    }
}
